package top.rinpsi.tools;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

public class ImgDeal {

    Map<String,BufferedImage> train;

    public ImgDeal(){}

    public ImgDeal(String path) throws IOException {
        train=new HashMap<String, BufferedImage>(10);
        File dir=new File(path);
        File[] fs=dir.listFiles();
        for (File f : fs) {
            train.put(f.getName().charAt(0) + "", ImageIO.read(f));
        }
    }

    private int isWhite(int colorInt) {
        Color color = new Color(colorInt);
        if (color.getRed() + color.getGreen() + color.getBlue() > 100) {
            return 1;
        }
        return 0;
    }

    public ImgDeal removeBackgroud(BufferedImage bi) throws Exception {
        int width = bi.getWidth();
        int height = bi.getHeight();
        for (int x = 0; x < height; ++x) {
            for (int y = 0; y < width; ++y) {
                if (isWhite(bi.getRGB(y, x)) == 1) {
                    bi.setRGB(y, x, Color.white.getRGB());
                } else {
                    bi.setRGB(y, x, Color.black.getRGB());
                }
            }
        }
        ImageIO.write(bi,"gif",new File("a.gif"));
        return this;
    }

    public java.util.List<BufferedImage> splitImage(BufferedImage img)
            throws Exception {
        java.util.List<BufferedImage> subImgs = new ArrayList<BufferedImage>();
        subImgs.add(img.getSubimage(6, 16, 8, 10));
        subImgs.add(img.getSubimage(18, 16, 8, 10));
        subImgs.add(img.getSubimage(30, 16, 8, 10));
        subImgs.add(img.getSubimage(42, 16, 8, 10));
        return subImgs;
    }

    public String getNum(BufferedImage img){
        Set<Map.Entry<String,BufferedImage>> set=train.entrySet();
        for (Map.Entry<String,BufferedImage> e:set) {
            if(compare(e.getValue(),img))
                return e.getKey();
        }
        return "#";
    }

    public boolean compare(BufferedImage a,BufferedImage b){
        int width=a.getWidth();
        int height=a.getHeight();
        int same=0;
        for(int x=0; x<width;x++){
            for(int y=0;y<height;y++){
                if(isWhite(a.getRGB(x,y))==isWhite(b.getRGB(x,y)))
                    same++;
            }
        }
        return ((double) same / (double) (width * height)) > 0.9;
    }

    public String getCode(InputStream in) throws Exception {
        StringBuilder result=new StringBuilder();
        BufferedImage img=ImageIO.read(in);
        removeBackgroud(img);
        java.util.List<BufferedImage> subimgs=splitImage(img);
        for(BufferedImage b:subimgs){
            result.append(getNum(b));
        }
        return result.toString();
    }
}
